﻿using System;
using System.ComponentModel;
using DoradoFramework.Core.GlobalTimer;
using Eflong.Utility;

namespace Eflong.Tasks
{
    /// <summary>
    /// 任务模板
    /// </summary>
    /// <typeparam name="T"></typeparam>
    internal abstract class TaskTemplate<T> : ICustomTask where T : new( )
    {
        #region Field

        protected string _taskName;
        protected bool _enabled = true;

        #endregion Field

        public TaskTemplate( )
        {
        }

        public TaskTemplate( string taskName , bool enabled = true )
        {
            _taskName = taskName;
            _enabled = enabled;
        }

        /// <summary>
        /// 任务句柄（用于控制任务的状态）
        /// </summary>
        protected static IGlobalTimerTaskHandle TaskHandle { get; set; }

        /// <summary>
        /// 创建任务
        /// </summary>
        /// <returns></returns>
        protected abstract bool CreateTask( );

        /// <summary>
        /// 销毁任务
        /// </summary>
        /// <returns></returns>
        protected abstract bool DisposeTask( );

        #region ICustomTask接口成员

        public virtual string TaskName
        {
            get
            {
                if ( !string.IsNullOrEmpty( _taskName ) )
                    return _taskName;

                object[ ] objs = this.GetType( ).GetCustomAttributes( typeof( DescriptionAttribute ) , false );

                if ( objs != null && objs.Length > 0 )

                    return ( objs[ 0 ] as DescriptionAttribute ).Description;

                return string.Empty;
            }
        }

        public virtual bool Enabled
        {
            get
            {
                return _enabled;
            }
            set
            {
                _enabled = value;
            }
        }

        /// <summary>
        /// 启动任务
        /// </summary>
        public void Start( )
        {
            try
            {
                if ( CreateTask( ) )
                {
                    string displayInfo = TaskName + "已经启动......";
                    LogWrapper.Logger.Info( displayInfo );
                }
            }
            catch ( Exception ex )
            {
                LogWrapper.Logger.Error( ex );
            }
        }

        /// <summary>
        /// 停止任务
        /// </summary>
        public void Stop( )
        {
            try
            {
                if ( DisposeTask( ) )
                {
                    string displayInfo = TaskName + "已经停止.....";

                    LogWrapper.Logger.Info( displayInfo );
                }
            }
            catch ( Exception ex )
            {
                LogWrapper.Logger.Error( ex );
            }
        }

        #endregion ICustomTask接口成员
    }
}